package com.credithc.eagleeye.api.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
 * 描 述: <br/>
 * 作 者: zhangjin<br/>
 * 创 建：2018年02月27日<br/>
 * 版 本：v1.0.0<br>
 * <p>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
@Slf4j
public class AESUtils {
    private final static String ENCODING_UTF8 = "utf-8";
    private static final String KEY_ALGORITHM = "AES";
    /**默认的加密算法*/
    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
    private String secretKeySeed = null;
    private String ivParameterSeed = null;
    public AESUtils(String secretKeySeed,String ivParameterSeed) {
        this.secretKeySeed = secretKeySeed;
        if (ivParameterSeed.length() != 16) {
            throw new RuntimeException("iv向量长度必须为16");
        }
        this.ivParameterSeed=ivParameterSeed;
    }
    public AESUtils(String secretKeySeed) {
        if (secretKeySeed.length() != 16) {
            throw new RuntimeException("iv向量长度必须为16");
        }
        this.secretKeySeed = secretKeySeed;
        this.ivParameterSeed=secretKeySeed;
    }
    /**
     * AES加密
     *
     * @param content
     *
     * @return String
     */
    public String aesEncrypt(String content) throws Exception {
        // AES加密
        byte[] encryptStr = encrypt(content, secretKeySeed,ivParameterSeed);
        // BASE64位加密
        return Base64.encodeBase64String(encryptStr);
    }
    /**
     * AES解密
     *
     * @param encryptStr
     *
     * @return String
     */
    public String aesDecrypt(String encryptStr) throws Exception {
        // BASE64位解密
        byte[] decodeBase64 = Base64.decodeBase64(encryptStr);
        // AES解密
        return new String(decrypt(decodeBase64, secretKeySeed,ivParameterSeed),ENCODING_UTF8);
    }

    /**
     * 生成加密秘钥
     *
     * @return
     */
    private static SecretKeySpec getSecretKeySpec(final String secretKeySeed) {
        try {
            /*
            //生成指定算法密钥生成器的 KeyGenerator 对象
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
            // 防止linux下 随机生成key
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(secretKeySeed.getBytes());
            //AES 要求密钥长度为 128
            keyGenerator.init(128, secureRandom);
            //生成一个密钥
            SecretKey secretKey = keyGenerator.generateKey();
            // 转换为AES专用密钥
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
            */
            //注意：ios不支持使用 KeyGenerator、SecureRandom、SecretKey 生成
            return new SecretKeySpec(secretKeySeed.getBytes(), "AES");
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return null;
    }

    /**
     * 生成向量秘钥
     *
     * @return
     */
    private static IvParameterSpec getIvParameterSpec(final String ivParameterSeed) {
        //使用CBC模式，需要一个向量iv，可增加加密算法的强度
        return new IvParameterSpec(ivParameterSeed.getBytes());
    }

    /**
     * 加密
     *
     * @param content
     *
     * @return byte[]
     */
    private static byte[] encrypt(String content, String secretKeySeed,String ivParameterSeed) throws Exception {
        // 创建密码器
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        // 初始化为加密模式的密码器
        cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(secretKeySeed),getIvParameterSpec(ivParameterSeed));
        // 加密
        return cipher.doFinal(content.getBytes(ENCODING_UTF8));
    }
    /**
     * 解密
     *
     * @param content
     *
     * @return byte[]
     */
    private static byte[] decrypt(byte[] content, String secretKeySeed,String ivParameterSeed) throws Exception {
        // 创建密码器
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        // 初始化为加密模式的密码器
        cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(secretKeySeed),getIvParameterSpec(ivParameterSeed));
        // 解密
        return cipher.doFinal(content);
    }

    public static void main(String[] args) throws Exception {
        String secretKeySeed = "devKey1234567890";
        String ivParameterSeed = "dlr-api-iv-param";
        AESUtils aesUtils = new AESUtils(secretKeySeed,ivParameterSeed);
        String message = "hello,world!";
        System.out.println("secretKeySeed：" + secretKeySeed);
        System.out.println("ivParameterSeed：" + ivParameterSeed);
        System.out.println("加密字符：" + message);
        System.out.println("加密后的字符：" + aesUtils.aesEncrypt(message));
        System.out.println("解密后的字符：" + aesUtils.aesDecrypt(aesUtils.aesEncrypt(message)));

    }
}
